#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成健康记录测试数据脚本
时间范围：2025-06-01 到 2025-11-15
每天生成1-2条记录
user_id: 2
"""

import os
import random
import time
from datetime import datetime, timedelta
import MySQLdb
from MySQLdb.cursors import DictCursor
from decouple import Config, RepositoryEnv

# 读取backend目录下的.env文件
# 先尝试.env文件
env_path = os.path.join(os.path.dirname(__file__), 'backend', '.env.dev')

print(f"使用环境文件: {env_path}")
config = Config(RepositoryEnv(env_path))

# 数据库连接配置 - 添加调试输出
DB_CONFIG = {
    'host': config('DB_HOST', default='localhost'),
    'port': config('DB_PORT', default=3306, cast=int),
    'user': config('DB_USER', default='dvhealth'),
    'passwd': config('DB_PASSWORD', default='dvhealthpassword'),
    'db': config('DB_NAME', default='dvhealth'),
    'charset': 'utf8mb4',
    'cursorclass': DictCursor
}

print(f"数据库配置: {DB_CONFIG}")

# 生成随机时间（当天内的随机时间）
def get_random_time(base_date):
    hour = random.randint(0, 23)
    minute = random.randint(0, 59)
    second = random.randint(0, 59)
    return datetime.combine(base_date, datetime.min.time()) + timedelta(hours=hour, minutes=minute, seconds=second)

# 生成身体指标记录
def generate_body_record(cursor, record_time):
    body_record = {
        'user_id': 2,
        'height': round(random.uniform(160.0, 180.0), 1),
        'weight': round(random.uniform(50.0, 80.0), 1),
        'low_pressure': round(random.uniform(60.0, 90.0), 1),
        'high_pressure': round(random.uniform(90.0, 140.0), 1),
        'blood_sugar': round(random.uniform(3.9, 6.1), 1),
        'heart_rate': round(random.uniform(60.0, 100.0), 1),
        'record_date': record_time.strftime('%Y-%m-%d %H:%M:%S'),
        'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    
    sql = """
    INSERT INTO body_records (user_id, height, weight, low_pressure, high_pressure, blood_sugar, heart_rate, record_date, created_at)
    VALUES (%(user_id)s, %(height)s, %(weight)s, %(low_pressure)s, %(high_pressure)s, %(blood_sugar)s, %(heart_rate)s, %(record_date)s, %(created_at)s)
    """
    cursor.execute(sql, body_record)
    print(f"生成身体指标记录: {record_time.date()}")

# 生成睡眠记录
def generate_sleep_record(cursor, record_time):
    sleep_quality = random.choice(['良好', '一般', '较差'])
    sleep_duration = round(random.uniform(6.0, 9.0), 1)
    
    # 计算入睡时间和起床时间 - 确保wakeup_time在早上6-12点之间，这样sleep_time会在前一天晚上
    wakeup_hour = random.randint(6, 12)
    wakeup_minute = random.randint(0, 59)
    wakeup_second = random.randint(0, 59)
    wakeup_time = datetime.combine(record_time.date(), datetime.min.time()) + timedelta(hours=wakeup_hour, minutes=wakeup_minute, seconds=wakeup_second)
    sleep_time = wakeup_time - timedelta(hours=sleep_duration)
    
    # 转换为字符串格式
    sleep_time_str = sleep_time.strftime('%Y-%m-%d %H:%M:%S')
    wakeup_time_str = wakeup_time.strftime('%Y-%m-%d %H:%M:%S')
    record_date_str = record_time.strftime('%Y-%m-%d %H:%M:%S')
    created_at_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    sleep_record = {
        'user_id': 2,
        'sleep_time': sleep_time_str,
        'wakeup_time': wakeup_time_str,
        'sleep_duration': sleep_duration,
        'sleep_quality': sleep_quality,
        'record_date': record_date_str,
        'created_at': created_at_str
    }
    
    # 详细调试输出
    print(f"调试信息 - 睡眠记录:")
    print(f"  sleep_time对象: {sleep_time}")
    print(f"  sleep_time字符串: {sleep_time_str}")
    print(f"  sleep_time类型: {type(sleep_time_str)}")
    print(f"  wakeup_time字符串: {wakeup_time_str}")
    print(f"  所有字段: {sleep_record}")
    
    # 直接拼接SQL语句进行调试
    sql_debug = f"INSERT INTO sleep_records (user_id, sleep_time, wakeup_time, sleep_duration, sleep_quality, record_date, created_at) VALUES (2, '{sleep_time_str}', '{wakeup_time_str}', {sleep_duration}, '{sleep_quality}', '{record_date_str}', '{created_at_str}')"
    print(f"  SQL语句: {sql_debug}")
    
    # 使用参数化查询 - 确保字段名与数据库完全匹配
    # 检查表结构中的实际字段名，可能存在大小写问题
    sql = """
    INSERT INTO sleep_records (user_id, sleep_time, wakeup_time, sleep_duration, sleep_quality, record_date, created_at)
    VALUES (%s, %s, %s, %s, %s, %s, %s)
    """
    
    # 使用位置参数而不是命名参数，避免字段名不匹配问题
    params = [
        sleep_record['user_id'],
        sleep_record['sleep_time'],
        sleep_record['wakeup_time'],
        sleep_record['sleep_duration'],
        sleep_record['sleep_quality'],
        sleep_record['record_date'],
        sleep_record['created_at']
    ]
    
    # 执行并检查受影响的行数
    rows_affected = cursor.execute(sql, params)
    print(f"  执行结果 - 受影响行数: {rows_affected}")
    print(f"生成睡眠记录: {record_time.date()}")

# 生成运动记录
def generate_sports_record(cursor, record_time):
    sport_types = ['跑步', '游泳', '骑行', '瑜伽', '健身']
    sport_type = random.choice(sport_types)
    
    # 根据运动类型设置不同的参数范围
    if sport_type == '跑步':
        duration = random.randint(20, 60)
        distance = round(random.uniform(3.0, 10.0), 1)
        calorie = round(random.uniform(200, 600), 1)
    elif sport_type == '游泳':
        duration = random.randint(30, 90)
        distance = round(random.uniform(1.0, 5.0), 1)
        calorie = round(random.uniform(300, 800), 1)
    elif sport_type == '骑行':
        duration = random.randint(45, 120)
        distance = round(random.uniform(10.0, 30.0), 1)
        calorie = round(random.uniform(300, 700), 1)
    elif sport_type == '瑜伽':
        duration = random.randint(30, 60)
        distance = 0.0
        calorie = round(random.uniform(100, 300), 1)
    else:  # 健身
        duration = random.randint(45, 90)
        distance = 0.0
        calorie = round(random.uniform(250, 600), 1)
    
    sports_record = {
        'user_id': 2,
        'type': sport_type,
        'during': duration,
        'distance': distance,
        'calorie': calorie,
        'record_date': record_time.strftime('%Y-%m-%d %H:%M:%S'),
        'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    
    sql = """
    INSERT INTO sports_records (user_id, type, during, distance, calorie, record_date, created_at)
    VALUES (%(user_id)s, %(type)s, %(during)s, %(distance)s, %(calorie)s, %(record_date)s, %(created_at)s)
    """
    cursor.execute(sql, sports_record)
    print(f"生成运动记录: {record_time.date()} - {sport_type}")

# 生成饮食记录
def generate_eating_record(cursor, record_time):
    foods_list = [
        {'name': '早餐：牛奶+鸡蛋+面包', 'calorie': 350},
        {'name': '午餐：米饭+鸡肉+蔬菜', 'calorie': 500},
        {'name': '晚餐：面条+鱼肉+豆腐', 'calorie': 450},
        {'name': '加餐：苹果', 'calorie': 80},
        {'name': '加餐：香蕉', 'calorie': 105},
        {'name': '加餐：酸奶', 'calorie': 150}
    ]
    
    food = random.choice(foods_list)
    intake = random.randint(100, 300)  # 摄入量（克）
    
    eating_record = {
        'user_id': 2,
        'foods_name': food['name'],
        'intake': intake,
        'calorie': food['calorie'],
        'record_date': record_time.strftime('%Y-%m-%d %H:%M:%S'),
        'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    }
    
    sql = """
    INSERT INTO eating_records (user_id, foods_name, intake, calorie, record_date, created_at)
    VALUES (%(user_id)s, %(foods_name)s, %(intake)s, %(calorie)s, %(record_date)s, %(created_at)s)
    """
    cursor.execute(sql, eating_record)
    print(f"生成饮食记录: {record_time.date()} - {food['name']}")

# 主函数
def main():
    # 时间范围
    start_date = datetime(2025, 6, 1)
    end_date = datetime(2025, 11, 15)
    
    try:
        # 连接数据库
        connection = MySQLdb.connect(**DB_CONFIG)
        with connection.cursor() as cursor:
            current_date = start_date
            while current_date <= end_date:
                # 每天生成1-2条记录
                records_per_day = random.randint(1, 2)
                
                for _ in range(records_per_day):
                    # 随机选择记录类型
                    # record_type = random.choice(['body', 'sleep', 'sports', 'eating'])
                    record_type = 'eating'

                    # 生成随机时间
                    record_time = get_random_time(current_date)
                    
                    # 生成对应类型的记录
                    if record_type == 'body':
                        generate_body_record(cursor, record_time)
                    elif record_type == 'sleep':
                        generate_sleep_record(cursor, record_time)
                    elif record_type == 'sports':
                        generate_sports_record(cursor, record_time)
                    elif record_type == 'eating':
                        generate_eating_record(cursor, record_time)
                    
                    # 随机延迟，避免记录时间过于集中
                    time.sleep(0.01)
                
                # 提交当天的记录
                connection.commit()
                
                # 移动到下一天
                current_date += timedelta(days=1)
        
        print("\n测试数据生成完成！")
        print(f"时间范围：{start_date.date()} 到 {end_date.date()}")
        print(f"user_id: 2")
        
    except Exception as e:
        print(f"生成测试数据时出错：{e}")
        if connection:
            connection.rollback()
    finally:
        if connection:
            connection.close()

if __name__ == '__main__':
    main()